{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ATN0AySQa38h"
      },
      "source": [
        "##### Copyright 2025 Google LLC."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "metadata": {
        "cellView": "form",
        "id": "80WmhK32a-_g"
      },
      "outputs": [],
      "source": [
        "# @title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sP8PQnz1QrcF"
      },
      "source": [
        "# Gemini API: Basic reasoning\n",
        "\n",
        "This notebook demonstrates how to use prompting to perform reasoning tasks using the Gemini API's Python SDK. In this example, you will work through a mathematical word problem using prompting."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bxGr_x3MRA0z"
      },
      "source": [
        "<a target=\"_blank\" href=\"https://colab.research.google.com/github/google-gemini/cookbook/blob/main/examples/prompting/Basic_Reasoning.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" height=30/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ysy--KfNRrCq"
      },
      "source": [
        "The Gemini API can handle many tasks that involve indirect reasoning, such as solving mathematical or logical proofs.\n",
        "\n",
        "In this example, you will see how the LLM explains given problems step by step."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "metadata": {
        "id": "Ne-3gnXqR0hI"
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/144.7 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m144.7/144.7 kB\u001b[0m \u001b[31m4.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ],
      "source": [
        "%pip install -U -q \"google-genai>=1.0.0\""
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "eomJzCa6lb90"
      },
      "source": [
        "## Configure your API key\n",
        "\n",
        "To run the following cell, your API key must be stored it in a Colab Secret named `GOOGLE_API_KEY`. If you don't already have an API key, or you're not sure how to create a Colab Secret, see [Authentication](https://github.com/google-gemini/cookbook/blob/main/quickstarts/Authentication.ipynb) for an example."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "v-JZzORUpVR2"
      },
      "outputs": [],
      "source": [
        "from google import genai\n",
        "from google.colab import userdata\n",
        "\n",
        "GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')\n",
        "client = genai.Client(api_key=GOOGLE_API_KEY)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "uAnckMv6s1X6"
      },
      "source": [
        "Additionally, select the model you want to use from the available options below:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "id": "H7RgspkDs2fs"
      },
      "outputs": [],
      "source": [
        "MODEL_ID = \"gemini-2.5-flash\"  # @param [\"gemini-2.5-flash-lite\", \"gemini-2.5-flash\", \"gemini-2.5-flash\",\"gemini-2.5-pro\",\"gemini-3-pro-preview\"] {\"allow-input\": true, \"isTemplate\": true}"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "L-Wt23A_uzFZ"
      },
      "source": [
        "## Examples\n",
        "\n",
        "Begin by defining some system instructions that will be include when you define and choose the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "metadata": {
        "id": "SabVqFgbu_Hd"
      },
      "outputs": [],
      "source": [
        "from google.genai import types\n",
        "\n",
        "system_prompt = \"\"\"\n",
        "  You are a teacher solving mathematical and logical problems. Your task:\n",
        "  1. Summarize given conditions.\n",
        "  2. Identify the problem.\n",
        "  3. Provide a clear, step-by-step solution.\n",
        "  4. Provide an explanation for each step.\n",
        "\n",
        "  Ensure simplicity, clarity, and correctness in all steps of your explanation.\n",
        "  Each of your task should be done in order and seperately.\n",
        "\"\"\"\n",
        "\n",
        "config = types.GenerateContentConfig(\n",
        "    system_instruction=system_prompt\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "HqAQdUvbe_1k"
      },
      "source": [
        "Next, you can define a logical problem such as the one below."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "metadata": {
        "id": "82qEUsfpz8mx"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Okay, I can help with that. Here's how we can break down this probability problem:\n",
              "\n",
              "1.  **Summarize given conditions.**\n",
              "\n",
              "    *   1 in 5 dice are weighted to always roll a 6. (20% of dice are weighted)\n",
              "    *   4 in 5 dice are fair. (80% of dice are fair)\n",
              "    *   A 6 was rolled.\n",
              "\n",
              "2.  **Identify the problem.**\n",
              "\n",
              "    *   We need to determine the probability that the die rolled was weighted, given that a 6 was rolled. This is a conditional probability problem.\n",
              "\n",
              "3.  **Provide a clear, step-by-step solution.**\n",
              "\n",
              "    Here's how we can use Bayes' Theorem to solve this:\n",
              "\n",
              "    *   **Define Events:**\n",
              "        *   `W` = The die is weighted.\n",
              "        *   `F` = The die is fair.\n",
              "        *   `6` = A 6 is rolled.\n",
              "\n",
              "    *   **State Known Probabilities:**\n",
              "        *   `P(W) = 1/5 = 0.2` (Probability of a die being weighted)\n",
              "        *   `P(F) = 4/5 = 0.8` (Probability of a die being fair)\n",
              "        *   `P(6|W) = 1` (Probability of rolling a 6 given the die is weighted)\n",
              "        *   `P(6|F) = 1/6` (Probability of rolling a 6 given the die is fair)\n",
              "\n",
              "    *   **Apply Bayes' Theorem:**\n",
              "        We want to find `P(W|6)` (Probability the die is weighted given a 6 was rolled).\n",
              "        Bayes' Theorem states:\n",
              "\n",
              "        `P(W|6) = [P(6|W) * P(W)] / P(6)`\n",
              "\n",
              "    *   **Calculate P(6):**\n",
              "        We need to find the overall probability of rolling a 6.  This can happen in two ways: rolling a 6 with a weighted die or rolling a 6 with a fair die.\n",
              "\n",
              "        `P(6) = P(6|W) * P(W) + P(6|F) * P(F)`\n",
              "        `P(6) = (1 * 0.2) + (1/6 * 0.8)`\n",
              "        `P(6) = 0.2 + 0.1333 = 0.3333` (approximately)\n",
              "\n",
              "    *   **Calculate P(W|6):**\n",
              "        Now we can plug the values into Bayes' Theorem:\n",
              "\n",
              "        `P(W|6) = (1 * 0.2) / 0.3333`\n",
              "        `P(W|6) = 0.2 / 0.3333`\n",
              "        `P(W|6) = 0.6` (approximately)\n",
              "\n",
              "    *   **Calculate P(F|6):**\n",
              "        We can also calculate `P(F|6)` (Probability the die is fair given a 6 was rolled).\n",
              "\n",
              "        `P(F|6) = [P(6|F) * P(F)] / P(6)`\n",
              "        `P(F|6) = [(1/6) * 0.8] / 0.3333`\n",
              "        `P(F|6) = 0.1333 / 0.3333`\n",
              "        `P(F|6) = 0.4` (approximately)\n",
              "\n",
              "4.  **Provide an explanation for each step.**\n",
              "\n",
              "    *   **Step 1: Define Events:**  Clearly defining the events helps to organize the problem and understand what probabilities we are working with.\n",
              "    *   **Step 2: State Known Probabilities:**  Listing the known probabilities is crucial for applying Bayes' Theorem correctly. We are given the probabilities of a die being weighted or fair, and we know the probabilities of rolling a 6 given each type of die.\n",
              "    *   **Step 3: Apply Bayes' Theorem:**  Bayes' Theorem is the fundamental tool for solving this type of conditional probability problem.  It allows us to update our belief about the die being weighted after observing the evidence (rolling a 6).\n",
              "    *   **Step 4: Calculate P(6):**  This step calculates the overall probability of rolling a 6, considering both weighted and fair dice. This is a necessary component of Bayes' Theorem.  We use the law of total probability to find P(6).\n",
              "    *   **Step 5: Calculate P(W|6):**  Finally, we plug the calculated values into Bayes' Theorem to find the probability that the die is weighted given that a 6 was rolled.\n",
              "\n",
              "    **Conclusion:**\n",
              "    `P(W|6) ≈ 0.6`\n",
              "    `P(F|6) ≈ 0.4`\n",
              "\n",
              "    It is more likely (60% probability) that the die was weighted than it was fair (40% probability), given that a 6 was rolled.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 6,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "from IPython.display import Markdown\n",
        "\n",
        "logical_problem = \"\"\"\n",
        "  Assume a world where 1 in 5 dice are weighted and have 100% to roll a 6.\n",
        "  A person rolled a dice and rolled a 6.\n",
        "  Is it more likely that the die was weighted or not?\n",
        "\"\"\"\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=logical_problem,\n",
        "    config=config,\n",
        ")\n",
        "Markdown(response.text)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "metadata": {
        "id": "u2ZDzuOYvMMy"
      },
      "outputs": [
        {
          "data": {
            "text/markdown": [
              "Okay, I will help you calculate the area of the triangle.\n",
              "\n",
              "1.  **Summarize given conditions:**\n",
              "    *   The base of the triangle, b = 6\n",
              "    *   The height of the triangle, h = 8\n",
              "\n",
              "2.  **Identify the problem:**\n",
              "    *   We need to find the area of the triangle given its base and height.\n",
              "\n",
              "3.  **Provide a step-by-step solution:**\n",
              "    *   **Step 1: Recall the formula for the area of a triangle.**\n",
              "        *   The area of a triangle is given by the formula: Area = (1/2) * base * height\n",
              "    *   **Step 2: Substitute the given values into the formula.**\n",
              "        *   Area = (1/2) * 6 * 8\n",
              "    *   **Step 3: Perform the calculation.**\n",
              "        *   Area = (1/2) * 48\n",
              "        *   Area = 24\n",
              "\n",
              "4.  **Provide an explanation for each step:**\n",
              "    *   **Step 1:** The formula Area = (1/2) \\* base \\* height is a fundamental formula in geometry for calculating the area of any triangle, given its base and corresponding height.\n",
              "    *   **Step 2:** We substitute the given values of base (b=6) and height (h=8) into the area formula.\n",
              "    *   **Step 3:** We first multiply the base and height (6\\*8=48), and then multiply the result by 1/2 (or divide by 2) to get the final area, which is 24.\n",
              "\n",
              "**Answer:** The area of the triangle is 24.\n"
            ],
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ]
          },
          "execution_count": 7,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "math_problem = \"\"\"\n",
        "  Given a triangle with base b=6 and height h=8, calculate its area\n",
        "\"\"\"\n",
        "\n",
        "response = client.models.generate_content(\n",
        "    model=MODEL_ID,\n",
        "    contents=math_problem,\n",
        "    config=config,\n",
        ")\n",
        "Markdown(response.text)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "4gJJr5AM5Bwl"
      },
      "source": [
        "## Next steps\n",
        "\n",
        "Be sure to explore other examples of prompting in the repository. Try creating your own prompts that include instructions on how to solve basic reasoning problems, or use the prompt given in this notebook as a template."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "name": "Basic_Reasoning.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
